﻿
using StreamServeDSIGenerator.Entities;
using StreamServeDSIGenerator.UI.Process;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.IO;
using System.Text.RegularExpressions;
using System.Threading;
using System.Windows.Forms;

namespace StreamServeDSIGenerator.UI.Win
{
    public partial class Main : Form
    {
        List<DataTemplate> DataTemplateList = new List<DataTemplate>();
        List<string> SearchResultList = new List<string>();
        int SearchResultListCursor = 0;
        public Main()
        {
            InitializeComponent();
            string defaultPath = Environment.ExpandEnvironmentVariables("%USERPROFILE%") + @"\Desktop";

            txtLocation.Text = defaultPath;
            folderBrowserDialog.SelectedPath = defaultPath;
        }

        private void btnGenerate_Click(object sender, EventArgs e)
        {
       //     string fileName = String.Empty;
       //     string fileExt = String.Empty;
       //     string dataText = String.Empty;
       //     string paramText1 = String.Empty;
       //     string fullFileName = String.Empty;
       //     string filelocation = String.Empty;

       //     int loopTime = 0;
       //     int paramStartIndex1 = 0;
       //     int paramEndIndex1 = 0;
       //     int paramRunningIndex = 0;

       //     filelocation = txtLocation.Text.Trim();
       //     fileName = txtFileName.Text.Trim();
       //     fileExt = txtExtension.Text.Trim().Replace(".","");
         
       //     if (String.IsNullOrEmpty(filelocation) || String.IsNullOrEmpty(fileName) || String.IsNullOrEmpty(fileExt))
       //     {
       //         MessageBox.Show("Invalid File Configurations value or Main Data Text is null.", "Validation Failure", MessageBoxButtons.OK, MessageBoxIcon.Error);
       //         return;
       //     }


       //     if (!Int32.TryParse(txtRepeats.Text.Trim(), out loopTime))
       //     {
       //         errorProviderDisplay.SetError(txtRepeats, "Repeat value must be numeric");
       //         return;
       //     }
       //     GenerationProgressBar.Value = 0;
       //     GenerationProgressBar.Maximum = loopTime;

       //     paramText1 = param1.Text.Trim();

       //     if (isParam1Increment.Checked)
       //     {
       //         if (!paramText1.Contains("{0}"))
       //         {
       //             errorProviderDisplay.SetError(param1, "Missing parameter in the Parameter 1 field.");
       //             return;
       //         }

       //         if (!Int32.TryParse(txtParam1StartIndex.Text.Trim(), out paramStartIndex1))
       //         {
       //             errorProviderDisplay.SetError(txtParam1StartIndex, "Invalid Parameter 1 Start Index value.");
       //             return;
       //         }

       //         if (!Int32.TryParse(txtParam1EndIndex.Text.Trim(), out paramEndIndex1))
       //         {
       //             errorProviderDisplay.SetError(txtParam1EndIndex, "Invalid Parameter 1 End Index value.");
       //             return;
       //         }

       //         if (paramStartIndex1 > paramEndIndex1)
       //         {
       //             errorProviderDisplay.SetError(txtParam1StartIndex, "End Index must be bigger than Start Index.");
       //             return;
       //         }

       //     }

       //     StatusLabel.Text = "Parameter(s) verification completed. Generating Data.";
       //     statusStrip.Refresh();
       //     Thread.Sleep(2000);

       //     btnGenerate.Enabled = false;


       //     String[,] GeneratedData  = new String[loopTime,2];
       //     paramRunningIndex = paramStartIndex1;
       ////     PopulateClass bc = new PopulateClass();



       //     int TemplateType = 0;

       //     if(rbSequentialTemplate.Checked)
       //     {
       //         TemplateType = 0;
       //     }
       //     else if(rbRandomTemplate.Checked)
       //     {
       //         TemplateType = 1;
       //     }


       //     GeneratedData = bc.populateDataTemplate(GeneratedData, loopTime, DataTemplateList, TemplateType);
            
       //     for (int currentLoop = 0; currentLoop < loopTime; currentLoop++)
       //     {
       //         if (isParam1Increment.Checked)
       //         {
       //             GeneratedData[currentLoop, 1] = paramText1.Replace("{0}", (paramRunningIndex).ToString("000"));
       //             paramRunningIndex++;
       //             if (paramRunningIndex > paramEndIndex1)
       //             {
       //                 paramRunningIndex = paramStartIndex1;
       //             }
       //         }
       //         else
       //         {
       //             GeneratedData[currentLoop, 1] = paramText1;
       //         }

       //         StatusLabel.Text = "Compiling template : " + (currentLoop+1) + " of " + loopTime;
       //         GenerationProgressBar.Value++;
       //         statusStrip.Refresh();
       //     }

       //     StatusLabel.Text = "Template compiling completed. Exporting to " + fileExt + " file(s).";
       //     statusStrip.Refresh();
       //     Thread.Sleep(2000);
       //     StatusLabel.Text = "Start exporting template.";
       //     GenerationProgressBar.Value = 0;
       //     statusStrip.Refresh();

           
       //     // Create dir if not exist
       //     DirectoryInfo dir = new DirectoryInfo(filelocation);
       //     if (!dir.Exists)
       //     {
       //         dir.Create();
       //     }
       //     /////
          

       //     //Export to Text File
       //     if (!isAppendAll.Checked)
       //     {
       //         for (int currentLoop = 0; currentLoop < loopTime; currentLoop++)
       //         {
       //             StatusLabel.Text = "Exporting : " + (currentLoop + 1) + " of " + loopTime + " expected file(s).";
       //             statusStrip.Refresh();
                   
       //             GeneratedData[currentLoop, 0] = GeneratedData[currentLoop, 0].Replace("{0}", GeneratedData[currentLoop, 1]);
       //             fullFileName = dir.FullName + "\\" + fileName + (currentLoop + 1) + "." + fileExt;
       //             using (StreamWriter sw = new StreamWriter(fullFileName, false))
       //             {
       //                 sw.WriteLine(GeneratedData[currentLoop, 0]);
       //             }

       //             GenerationProgressBar.Value++;
       //         }
       //     }
       //     else
       //     {
       //         fullFileName = dir.FullName + "\\" + fileName + "." + fileExt;
       //         for (int currentLoop = 0; currentLoop < loopTime; currentLoop++)
       //         {
       //             StatusLabel.Text = "Exporting : " + (currentLoop + 1) + " of " + loopTime + " expected file(s).";
       //             statusStrip.Refresh();

       //             GeneratedData[currentLoop, 0] = GeneratedData[currentLoop, 0].Replace("{0}", GeneratedData[currentLoop, 1]);
                
       //             using (StreamWriter sw = new StreamWriter(fullFileName, true))
       //             {
       //                 sw.WriteLine(GeneratedData[currentLoop, 0]);
       //             }

       //             GenerationProgressBar.Value++;
       //         }

       //     }


       //     StatusLabel.Text = "Export Completed";
       //     statusStrip.Refresh();
       //     btnGenerate.Enabled = true;
       //     MessageBox.Show("File(s) generation completed.", "Operation Completion", MessageBoxButtons.OK, MessageBoxIcon.Information);
         
        }

        private void isParam1Increment_CheckedChanged(object sender, EventArgs e)
        {
            txtParam1StartIndex.Enabled = isParam1Increment.Checked;
            txtParam1EndIndex.Enabled = isParam1Increment.Checked;
        }

        private void btnMenuStripExit_Click(object sender, EventArgs e)
        {
            Application.Exit();
        }

        private void btnFolderLocation_Click(object sender, EventArgs e)
        {
           
        }

        private void btnDataTemplateClear_Click(object sender, EventArgs e)
        {
            txtTemplate.Text = "";
            listDataTemplate.ClearSelected();
            btnAddTemplate.Text = "Add Template";
        }

        private void listDataTemplate_SelectedIndexChanged(object sender, EventArgs e)
        {
            //UpdateMainControl umc = new UpdateMainControl();
            //umc.TemplateListBox = listDataTemplate;
            //umc.btnAddUpdate = btnAddTemplate;
            //umc.txtTemplate = txtTemplate;
            //umc.TemplateListBoxSelectedIndexChanged(DataTemplateList);
            //if (listDataTemplate.Items.Count > 0 && listDataTemplate.SelectedIndex >= 0)
            //{
            //    txtTemplate.Text = DataTemplateList[listDataTemplate.SelectedIndex].DataTemplateText;
            //}
        }

        private void btnAddTemplate_Click(object sender, EventArgs e)
        {
            string templateData = txtTemplate.Text.Trim();
            
            if (String.IsNullOrEmpty(templateData))
            {
                errorProviderDisplay.SetError(txtTemplate, "Invalid Template value.");
                return;
            }

            DataTemplate entDT = new DataTemplate();
            entDT.DataTemplateText = templateData;
            DataTemplateList.Add(entDT);

            repopulateListItem();
            txtTemplate.Text = "";
        }

        private void btnListBoxDeleteSelected_Click(object sender, EventArgs e)
        {

            if (listDataTemplate.SelectedIndex >= 0)
            {
                DialogResult dialogResult = MessageBox.Show("Do you want to delete selected data template?", "Delete Selected Data Template", MessageBoxButtons.YesNo, MessageBoxIcon.Question);

                if (dialogResult == DialogResult.Yes)
                {
                    DataTemplateList.RemoveAt(listDataTemplate.SelectedIndex);
                    listDataTemplate.Items.RemoveAt(listDataTemplate.SelectedIndex);
                    repopulateListItem();
                }
            }
           
        }

        private void repopulateListItem()
        {
            listDataTemplate.Items.Clear();
            for (int i = 0; i < DataTemplateList.Count; i++)
            {
                listDataTemplate.Items.Add("Template" + (i + 1));
            }
            listDataTemplate.ClearSelected();
            btnAddTemplate.Enabled = true;
        }

        private void btnFind_Click(object sender, EventArgs e)
        {
            //string template = String.Empty;
            //string regexStr = String.Empty;

            //btnPrevSearch.Enabled = false;
            //btnNextSearch.Enabled = false;

            //template = txtTemplate.Text.Trim();
            //SearchDialog promptSearch = new SearchDialog();

            //if (promptSearch.ShowDialog(this) == DialogResult.OK)
            //{
              
            //    regexStr = promptSearch.txtRegex.Text.Trim();
            //    char[] delimiters = new char[] { '#' };
            //    String[] TextBlock = template.Split(delimiters, StringSplitOptions.RemoveEmptyEntries);


            //    //SearchResultList = Regex.Matches(template, regexStr, RegexOptions.IgnoreCase)
            //    //        .OfType<Match>()
            //    //        .Select(m => m.Groups[0].Value)
            //    //        .ToList<String>();

            //    for (int i = 0; i < TextBlock.Length; i++)
            //    {
            //        string CurrTextBlock = TextBlock[i].Trim();

            //        if (Regex.Match(CurrTextBlock, regexStr, RegexOptions.IgnoreCase).Success)
            //        {
            //            SearchResultList.Add(CurrTextBlock);
            //        }
            //    }

            //    lblSearchResult.Text = SearchResultList.Count + " result(s) found!";

            //    if (SearchResultList.Count < 1)
            //    {
            //        return;
            //    }
            //    btnPrevSearch.Enabled = true;
            //    btnNextSearch.Enabled = true;

            //    txtTemplate.Focus();
            //    txtTemplate.SelectionStart = txtTemplate.Text.IndexOf(SearchResultList[SearchResultListCursor]);
            //    txtTemplate.SelectionLength = SearchResultList[SearchResultListCursor].Length;
            //    txtTemplate.ScrollToCaret();
            //    //int startIndexOfSearch =template.IndexOf("#simonlohzl@hotmail.com", 0, StringComparison.Ordinal);
            ////int endIndexOfSearch = template.LastIndexOf("#simonlohzl@hotmail.com", 0, StringComparison.Ordinal);

            //////this.txtTemplate.SelectionStart = startIndexOfSearch;
            //////this.txtTemplate.SelectionLength = endIndexOfSearch - startIndexOfSearch;

            ////this.txtTemplate.Text = template.LastIndexOf("#simonlohzl@hotmail.com", 0, StringComparison.Ordinal).ToString();
            //    //this.txtTemplate.Text = promptSearch.txtRegex.Text;

            //  //  template.IndexOf("#simonlohzl@hotmail.com", 
            //    //CompareInfo.

            //    //    FindNLSString
            //    //Match match = Regex.Match(template, @"#^([a-zA-Z0-9_\-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$", RegexOptions.IgnoreCase);

            //    //txtTemplate.Text = match.Success.ToString();



            //}
            //else
            //{
            //    lblSearchResult.Text = "No result(s) found!";
            //    btnNextSearch.Enabled = false;
            //    btnPrevSearch.Enabled = false;
            //}

            //promptSearch.Dispose();
        }

        private void btnNextSearch_Click(object sender, EventArgs e)
        {
            SearchResultListCursor += 1;

            if (SearchResultListCursor >= SearchResultList.Count)
            {
                SearchResultListCursor = 0;
            }
            txtTemplate.Focus();
            txtTemplate.SelectionStart = txtTemplate.Text.IndexOf(SearchResultList[SearchResultListCursor]);
            txtTemplate.SelectionLength = SearchResultList[SearchResultListCursor].Length;
            txtTemplate.ScrollToCaret();
        }

        private void btnPrevSearch_Click(object sender, EventArgs e)
        {
            SearchResultListCursor -= 1;

            if (SearchResultListCursor < 0)
            {
                SearchResultListCursor = SearchResultList.Count-1;
            }
            txtTemplate.Focus();
            txtTemplate.SelectionStart = txtTemplate.Text.IndexOf(SearchResultList[SearchResultListCursor]);
            txtTemplate.SelectionLength = SearchResultList[SearchResultListCursor].Length;
            txtTemplate.ScrollToCaret();
        }

        private void rawImportToolStripMenuItem_Click(object sender, EventArgs e)
        {
            importDialogControl control = new importDialogControl();

            control.mainForm = this;
            control.OpenDialog();
            //importDialog childDialog = new importDialog();

            //childDialog.validate += childDialog_validate;
            //if (childDialog.ShowDialog(this) == System.Windows.Forms.DialogResult.OK)
            //{
            //    Stream stream = null;
            //    string line = String.Empty;
            //    string blockStart = String.Empty;
            //    string fileName = String.Empty;
                
            //    blockStart = childDialog.txtBlockStart.Text.Trim();
            //    fileName = childDialog.txtFileName.Text.Trim();
            //    bool isFirstLine = true;
            //    DataTemplate importChunkDataTemplate = new DataTemplate();
            //    txtTemplate.Text = "";

                

                //try
                //{
                //    if ((stream = File.OpenRead(fileName)) != null)
                //    {
                //        DataTemplateList.Clear();


                //        using (StreamReader file = new StreamReader(stream))
                //        {
                //            while ((line = file.ReadLine()) != null)
                //            {
                //                if (!isFirstLine && line.StartsWith(blockStart, StringComparison.Ordinal))
                //                {
                //                    DataTemplateList.Add(importChunkDataTemplate);
                //                    importChunkDataTemplate = new DataTemplate();
                //                }

                //                importChunkDataTemplate.DataTemplateText += line + Environment.NewLine;
                //                isFirstLine = false;

                //                //    if(file.rea
                //            }
                //            if (!String.IsNullOrEmpty(importChunkDataTemplate.DataTemplateText))
                //            {
                //                DataTemplateList.Add(importChunkDataTemplate);
                //                importChunkDataTemplate = null;
                //            }
                //            //while (file.Peek()>=0)
                //            //{
                //            //    using(line = file.rea
                //            //}
                //            //    file.rea
                //            //    //while ((line = file.ReadLines().Last()) != null)
                //            //    //{
                //            //    //    //if(file.l
                //            //    //    //if (!isFirstLine && line.StartsWith("0#", StringComparison.Ordinal))
                //            //    //    //{
                //            //    //    //    DataTemplateList.Add(importChunkDataTemplate);
                //            //    //    //    importChunkDataTemplate = new DataTemplate();
                //            //    //    //}


                //            //    //    //


                //            //    //}
                //        }
                //    }
                //}
                //catch (Exception ex)
                //{
                //    MessageBox.Show("Unable to open selected template text file.", "Cannot Open File", MessageBoxButtons.OK, MessageBoxIcon.Error);
                //}

            //    repopulateListItem();
            //}
            
            //DialogResult dialogResult = importFileDialog.ShowDialog();
            //txtTemplate.Text = "";
            //if (dialogResult == System.Windows.Forms.DialogResult.OK)
            //{
            
        }

      

     

        private void txtTemplate_TextChanged(object sender, EventArgs e)
        {
            if (listDataTemplate.SelectedIndex >= 0)
            {
                DataTemplateList[listDataTemplate.SelectedIndex].DataTemplateText = txtTemplate.Text.Trim();
            }
        }

        private void Main_MouseUp(object sender, MouseEventArgs e)
        {
            listDataTemplate.ClearSelected();
            txtTemplate.Text = "";
        }

        private void btnClearTemplateCollection_Click(object sender, EventArgs e)
        {
            DataTemplateList.Clear();
            repopulateListItem();
            txtTemplate.Text = "";
            btnAddTemplate.Enabled = true;
        }

        private void txtLocation_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            DialogResult dr = folderBrowserDialog.ShowDialog();

            if (dr == System.Windows.Forms.DialogResult.OK)
            {
                txtLocation.Text = folderBrowserDialog.SelectedPath;
            }
        }

      

      




    }
}
